<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row  v-show="!switchFlag" class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="档案名称：" prop="docName">
                        <Input class="query-form-el"  type="text" v-model="form1.docName" ></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="归档单位：" prop="docOrgId" >
                        <cascaderDom class="query-form-el" style="padding-top: 4px" ref="trainOrg"  @setOrgInfo="setOrgId" @setOrgName="setOrgName"  :currentOrgId = "staffOrgId"
                                     :currentOrgName = "staffOrgName"   :orgTree = "true"  ></cascaderDom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text"  >展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row  v-show="switchFlag" class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="档案名称：" prop="docName">
                        <Input class="query-form-el"  type="text" v-model="form1.docName" ></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="归档单位：" prop="docOrgId" >
                        <cascaderDom class="query-form-el" style="padding-top: 4px" ref="trainOrg"  @setOrgInfo="setOrgId" @setOrgName="setOrgName"  :currentOrgId = "staffOrgId"
                                     :currentOrgName = "staffOrgName"   :orgTree = "true"  ></cascaderDom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="事件类型：" prop="eventTypeId">
                        <Select filterable v-model="form1.eventTypeId"  >
                            <Option v-for="item in eventTypeList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                        </Select>
                    </FormItem>
                </Col>

            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="24">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text"  >收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset"   >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>

            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
                    <!--<Button size="large"  class="ivu-btn-delete" icon="md-trash" @click="batDelete">删除</Button>-->
                </Col>
            </Row>
        </Form>

        <Table ref='table' :height="tableHeight" :loading="loading" size="small" no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows'
               border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal  title="总结归档" :transfer=false  v-model="model1"  :width=600>
            <Row>
                <Col span="24">
                    <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom"  label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7" >
                                <FormItem label="档案名称：" prop="docName">
                                    <Input type="text" v-model="form1datacopy.docName" ></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="归档单位：" prop="docOrgId">
                                    <cascaderDom class="query-form-el" style="padding-top: 4px" ref="carOrg"  @setOrgInfo="setCurrentOrgId" @setOrgName="setCurrentOrgName"  :currentOrgId = "currentOrgId"
                                                 :currentOrgName = "currentOrgName"   :orgTree = "true"  ></cascaderDom>
                                </FormItem>
                            </Col>
                            <Col span="7" >
                                <FormItem label="归档人：" prop="archiver">
                                    <cascaderDom  ref="childUser" @setOrgInfo="setUserId" @setOrgname="setUserName"  :setCurrentName="setCurrentName"  ></cascaderDom>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="7" >
                                <FormItem label="事件名称：" prop="eventName" >
                                    <Input type="text" v-model="form1datacopy.eventName" ></Input>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="归档时间：" prop="archiveDate">
                                    <DatePicker v-model="form1datacopy.archiveDate" type="date" placeholder="请输入" ></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="7">
                                <FormItem label="事件类型：" prop="eventTypeId">
                                    <Select filterable v-model="form1datacopy.eventTypeId"  >
                                        <Option v-for="item in eventTypeList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>


                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="附件：" prop="attachId">
                                    <Upload
                                            multiple
                                            ref="upload"
                                            type="drag"
                                            :show-upload-list="true"
                                            :before-upload="beforeUploadOther"
                                            :action="upUrl"
                                            :max-size="10240"
                                    >
                                        <div style="padding: 10px 0;height: 50px">
                                            <Icon type="ios-cloud-upload" size="32" style="color: #3399ff"></Icon>
                                        </div>
                                    </Upload>
                                    <div v-for="(file,index) in files" :key="index" >
                                        已选择附件: {{ file.name }}    <Button  type="text" icon="md-trash" @click="deleteFile(index)"  style="margin-left: 20px;margin-bottom: 3px" />
                                    </div>
                                </FormItem>
                            </Col>


                        </Row>


                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="23">
                                <FormItem label="档案说明：" prop="archiveDes">
                                    <Input v-model="form1datacopy.archiveDes" type="textarea" :rows="2" />
                                </FormItem>
                            </Col>


                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="23">
                                <FormItem label="备注：" prop="notes">
                                    <Input v-model="form1datacopy.notes" type="textarea" :rows="2" />
                                </FormItem>
                            </Col>


                        </Row>
                       <!-- <Row type="flex" justify="center" class="code-row-bg">
                            <Col span="23" >
                                <FormItem>
                                    <Button type="primary"  class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')" >确定</Button>
                                    <Button type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                                </FormItem>
                            </Col>
                        </Row>-->
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary"  class='ivu-btn-save' :loading="buttonLoading" @click="submit('form1datacopy')" >确定</Button>
                <Button type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
            </div>
        </Modal>
        <Modal title="总结归档" class="modal-view-detail" :transfer=false v-model="model2"  :width=800 >
            <Row>
                <Col span="24">
                    <Form  :model="showdata" :label-width="160" >
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="演练名称：" prop="档案名称">
                                    {{showdata.docName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="归档单位：" prop="orgName" >
                                    {{showdata.orgName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="归档人：" prop="userName">
                                    {{showdata.userName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="事件名称：" prop="eventName" >
                                    {{showdata.eventName}}
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="归档时间：" prop="archiveDate">
                                    {{showdata.archiveDate}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="事件类型：" prop="eventTypeName">
                                    {{showdata.eventTypeName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="计划文档：" prop="attachId ">
                                    <span  v-for="(file,index) in files" :key="index" style="margin-right: 10px">
                                        <a :href="downloadUrl+ '/' + file.id">{{file.fileName}}</a>
                                    </span>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="档案说明：" prop="archiveDes ">
                                    {{showdata.archiveDes }}
                                </FormItem>
                            </Col>

                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="备注：" prop="notes ">
                                    {{showdata.notes }}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
            </div>
        </Modal>

    </Layout>
</template>

<script>
    import {Api} from '../../../../api'
    import cascaderDom from "../../../../components/cascader-dom.vue"

    export default {
        components:{
            cascaderDom,

        },
        data(){
            return{
                setCurrentName:{},
                downloadUrl:Api.downloadPTWSchemeFile,
                upUrl:Api.uploadPTWSchemeFile,
                switchFlag : false,
                form1: {
                },
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                dataTable:[],
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed:'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {
                        title: '档案名称',
                        width: 150,
                        align: 'center',
                        key:'docName',
                    },
                    {
                        title: '事件名称',
                        width: 150,
                        align: 'center',
                        key:'eventName',
                    },
                    {
                        title: '事件类型',
                        width: 150,
                        align: 'center',
                        key:'eventTypeName',
                    },
                    {
                        title: '归档单位',
                        width: 150,
                        align: 'center',
                        key:'orgName',
                    },
                    {
                        title: '归档人',
                        width: 150,
                        align: 'center',
                        key:'userName',
                    },
                    {
                        title: '归档时间',
                        width: 150,
                        align: 'center',
                        key:'archiveDate',
                        render:(h,params)=>{
                            return h('div',[
                                (this.formatDate(new Date(params.row.archiveDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },
                    {
                        title: '档案说明',
                        width: 150,
                        align: 'center',
                        key:'archiveDes',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 0,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params,1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params,2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color:'red'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    },

                ],
                ruleCustom : {
                    docName: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    docOrgId: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                    archiver: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                    archiveDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],

                    eventName: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    eventTypeId: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                },
                add:false,
                model1:false,
                model2:false,
                showdata: {},
                eventTypeList: [],
                staffOrgId:'',
                staffOrgName:'',
                form1datacopy:{



                },
                files :[],
                tableHeight:10,
                buttonLoading:false,
                loading: false,
                currentOrgId : '',
                currentOrgName: '',
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.selectCodingSort();
            this.query();
        },
        methods:{
            beforeUploadOther(file) {
                this.files.push(file);
                return false;
            },
            deleteFile(index){
                this.files.splice(index,1);
            },
            setUserName(data) {
                this.form1datacopy.userName  = data;
            },
            setUserId(data) {
                this.form1datacopy.archiver = data[data.length - 1];
            },
            deleteData(params) {
                let url = Api.deleteEmergencyDoc;
                this.$http.delete(url +'/'+ params.row.docId, {params: {}}).then((res) => {
                    if (res.data.status === 200) {
                        this.$Message.success('成功');
                        this.query()
                    }else if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);

                    }
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })
            },
            setOrgId(data) {
                this.form1.docOrgId = data[data.length - 1];
            },
            setOrgName(data) {
                this.form1.orgName = data;
            },
            setCurrentOrgId(data) {
                this.form1datacopy.docOrgId = data[data.length - 1];
            },
            setCurrentOrgName(data) {
                this.form1datacopy.orgName = data;
            },
            getSelectRows (rows){
                this.deleteRows = rows;
            },
            batDelete(){

            },
            addInfo(){
                this.form1datacopy = {

                };
                this.files = [];
                this.setCurrentName  = {};
                this.currentOrgId  = '';
                this.currentOrgName = '';
                this.model1 = true;
                this.add = true;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            handleCancel() {
                this.form1datacopy = {

                };
                this.model1 = false;
            },
            selectCodingSort(){
                this.$http.get(Api.queryCodeDetailBySortId + '/ET-000001', {params: {}}).then((res) => {
                    this.eventTypeList  = res.data.data;
                });
            },
            switchQuery(flag){
                this.switchFlag = flag;
                if(!this.switchFlag){
                    this.tableHeight = window.innerHeight - 220;
                }else{
                    this.tableHeight = window.innerHeight - 315;
                }
            },
            reset() {
                this.form1 = {};
                this.staffOrgId='';
                this.staffOrgName='';

            },
            query() {this.loading = true ;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize
                };
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.queryEmergencyDoc;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            showData(data, flag) {
                this.currentOrgId  = data.row.docOrgId;
                this.currentOrgName = data.row.orgName;

                if (flag == 1) {
                    //查看页面
                    this.$http.get(Api.uploadPTWFiles+"/"+data.row.docId+"/files/file", ).then((res) => {
                        this.files = res.data.data;
                        console.log(this.files)

                    }).catch(e => {
                        this.$Message.error("数据获取失败")
                    });
                    this.showdata = data.row;
                    this.showdata.archiveDate = this.formatDate(new Date(this.showdata.archiveDate), 'yyyy-MM-dd');
                    this.model2 = true;
                } else {
                    this.files = [];
                    //修改页面
                    this.add = false;
                    // this.form1datacopy.purchaseDate = this.formatDate(new Date(this.showdata.purchaseDate), 'yyyy-MM-dd');
                    this.form1datacopy = JSON.parse(JSON.stringify(data.row));
                    this.setCurrentName  = { value :data.row.archiver, label :data.row.userName };
                    this.model1 = true;
                }
            },formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            async upload(){

            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        this.form1datacopy.archiveDate = this.formatDate(new Date(this.form1datacopy.archiveDate), 'yyyy-MM-dd');
                        if (this.files.length>0) {
                            if(this.add){
                                this.$http.post(Api.saveEmergencyDoc, this.form1datacopy).then((res) => {
                                    if (res.data.status === 200) {
                                        let ids = res.data.data;
                                        let formData = new FormData();
                                        for(let i =0;i < this.files.length;i ++){
                                            formData.append("files", this.files[i]);
                                        }
                                        //多附件上传
                                        this.$http.post(Api.uploadPTWFiles + '/' + ids + '/files/file', formData).then((res) => {
                                            if (res.data.result == "success") {
                                                this.$Message.success("保存成功");
                                                this.model1 = false;
                                                this.query();
                                            } else {
                                                this.$Message.error("附件上传失败");
                                            }
                                        }).catch(e => {
                                            console.log(e);
                                            this.$Message.error("数据获取失败");
                                        })
                                    }else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                        this.model1 = false;
                                    }this.buttonLoading = false

                                }).catch(e => {
                                    this.model1 = false;
                                    this.query();
                                    this.$Message.error("数据获取失败")
                                })
                            }else{
                                this.$http.post(Api.updateEmergencyDoc, this.form1datacopy).then((res) => {
                                    if (res.data.status === 200) {
                                        let ids = res.data.data;
                                        let formData = new FormData();
                                        for(let i =0;i < this.files.length;i ++){
                                            formData.append("files", this.files[i]);
                                        }
                                        //多附件上传
                                        this.$http.post(Api.uploadPTWFiles + '/' + ids + '/files/file', formData).then((res) => {
                                            if (res.data.result == "success") {
                                                this.$Message.success("保存成功");
                                                this.model1 = false;
                                                this.query();
                                            } else {
                                                this.$Message.error("附件上传失败");
                                            }
                                        }).catch(e => {
                                            console.log(e);
                                            this.$Message.error("数据获取失败");
                                        })
                                        this.buttonLoading = false
                                    }else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                        this.model1 = false;
                                    }

                                }).catch(e => {
                                    this.model1 = false;
                                    this.query();
                                    this.$Message.error("数据获取失败")
                                })
                            }

                        }else{
                            if(this.add){
                                this.$http.post(Api.saveEmergencyDoc, this.form1datacopy).then((res) => {
                                    if (res.data.status === 200) {
                                        this.$Message.success('成功');
                                        this.model1 = false;
                                        this.query()

                                    }else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                        this.model1 = false;
                                    }

                                }).catch(e => {
                                    this.model1 = false;
                                    this.query();
                                    this.$Message.error("数据获取失败")
                                })
                            }else{
                                this.$http.post(Api.updateEmergencyDoc, this.form1datacopy).then((res) => {
                                    if (res.data.status === 200) {
                                        this.$Message.success('成功');
                                        this.model1 = false;
                                        this.query()

                                    }else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                        this.model1 = false;
                                    }

                                }).catch(e => {
                                    this.model1 = false;
                                    this.query();
                                    this.$Message.error("数据获取失败")
                                })
                            }
                        }

                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },

        },
        watch:{
            "model1":function(qw,er){
                if(qw && this.model1){
                    setTimeout(()=>{
                        this.$refs.carOrg.setCurrentOrg();
                        this.$refs.childUser.setCurrentUser();
                    },100)
                }else{
                    this.$refs.carOrg.setCurrentOrg();
                    this.$refs.childUser.setCurrentUser();
                }
            },

        },

    }
</script>

<style lang='css' scoped>
    @import '../../../../index.css';
</style>
